#include <stdio.h>
#include <string.h>
#include <errno.h>
#ifdef _WIN32
#include <Windows.h>
#else
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#endif//_WIN32

static void list_dir(const char *path)
{
    int ret;
#ifdef _WIN32
    char pathbuf[1024];
    HANDLE    hFind;
    WIN32_FIND_DATAA findData = {0};

    sprintf_s(pathbuf, sizeof(pathbuf), "%s\\*.*", path);
    hFind = FindFirstFileA(pathbuf, &findData);
    if (INVALID_HANDLE_VALUE == hFind)
    {
        ret = GetLastError();
        printf("FindFirstFileA[%s] failed!ret=%d\n", path, ret);
        return;
    }
    do
    {
        if (0 == strcmp(".", findData.cFileName) || 0 == strcmp("..", findData.cFileName))
        {
            continue;
        }
        printf("%s\n", findData.cFileName);
    } while (FindNextFileA(hFind, &findData));
    FindClose(hFind);
#else
    DIR *dir = NULL;
    struct dirent *dp = NULL;
    struct stat st;

    if (stat(path, &st) < 0)
    {
        printf("Invalid path: %s\n", path);
        return;
    }

    if (!S_ISDIR(st.st_mode))
    {
        printf("Path<%s> isn't directory!\n", path);
        return;
    }

    dir = opendir(path);
    if (NULL == dir)
    {
        ret = errno;
        printf("opendir[%s] failed!ret=%d\n", path, ret);
        return;
    }

    while (NULL != (dp = readdir(dir)))
    {
        if (0 == strcmp(".", dp->d_name) || 0 == strcmp("..", dp->d_name))
        {
            continue;
        }
        printf("%s\n", dp->d_name);
    }
    closedir(dir);
#endif//_WIN32
}

int main(int argc, char **argv)
{
    const char *path = "./";

    if (argc >= 2)
    {
        path = argv[1];
    }
    list_dir(path);
    return 0;
}
